﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace eStock.Common
{
    static class ErrorHandler
    {
        public static string LastError { get; set; }
        public static string LastMessage { get; set; }
        public static Exception LastException { get; set; }

        public static void ThrowError(Exception ex,string msgTitle, bool exitApplication = true)
        {
            if (!Application.Current.Dispatcher.CheckAccess())
            {
                Application.Current.Dispatcher.Invoke(new Action(() => ThrowError(ex,msgTitle, exitApplication)));
                return;
            }
            if (ex != null)
            {
                LastException = ex;
                if (string.IsNullOrEmpty(msgTitle))
                    LastError = "Es ist ein Fehler aufgetreten:\n" + ex.Message;
                else
                    LastError = msgTitle + "\n" + ex.Message;

                Exception inner = ex.InnerException;
                if (inner != null)
                    LastError += "\n\n---\nDetails:";
                while (inner != null)
                {
                    LastError += "\n[" + inner.Message + "]";
                    inner = inner.InnerException;
                }
            }
            else
            {
                LastError = "Es ist ein unbekannter Fehler aufgetreten.";
            }
            MessageBox.Show(LastError, "Es ist ein Fehler aufgetreten", MessageBoxButton.OK, MessageBoxImage.Error);
            if (exitApplication)
            {
                Logging.WriteLog("Closing application after Exception \n(Details: " + LastError + ")");
                Application.Current.Shutdown();
            }
        }
    }
}
